package com.jerome.election.storage;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

/**
 * File utility class.
 *
 * @author Jerome
 * @date 2023/8/7
 */
public class FileUtil {

    /**
     * Writes a string to a file.
     *
     * @param fileName The system-dependent filename.
     * @param content  String to be written to the file.
     * @param append   If <code>true</code>, data will be written to the end of the file; otherwise, it will overwrite the file.
     * @throws IOException if an I/O error occurs.
     */
    public static synchronized void write2File(String fileName, String content, boolean append) throws IOException {
        try (BufferedWriter out = new BufferedWriter(new FileWriter(fileName, append))) {
            out.write(content);
        }
    }

    /**
     * Reads the contents of a file.
     *
     * @param fileName The name of the file to read from.
     * @return The content of the file as a string.
     * @throws IOException if an I/O error occurs.
     */
    public static synchronized String readFile(String fileName) throws IOException {
        try (BufferedReader in = new BufferedReader(new FileReader(fileName))) {
            StringBuilder sb = new StringBuilder();
            String str;
            while ((str = in.readLine()) != null) {
                sb.append(str);
            }
            return sb.toString();
        }
    }


    /**
     * Serialize an object to a file.
     *
     * @param object   The object to be serialized.
     * @param fileName The file where the object will be stored.
     * @throws IOException if an I/O error occurs.
     */
    public static void serialize(Object object, String fileName) throws IOException {
        try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File(fileName)))) {
            objectOutputStream.writeObject(object);
        }
    }

    /**
     * Deserialize an object from a file.
     *
     * @param fileName The file from which the object will be deserialized.
     * @return The deserialized object.
     * @throws IOException            if an I/O error occurs.
     * @throws ClassNotFoundException if the class of the object cannot be found.
     */
    public static Object deserialize(String fileName) throws IOException, ClassNotFoundException {
        try (ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(new File(fileName)))) {
            Object object = objectInputStream.readObject();
            return object;
        }
    }

    /**
     * 解压文件
     *
     * @param zipFile：需要解压缩的文件
     * @param descDir：解压后的目标目录
     */
    public static void unZipFiles(File zipFile, String descDir) throws IOException {
        File destFile = new File(descDir);
        if (!destFile.exists()) {
            destFile.mkdirs();
        }
        // 解决zip文件中有中文目录或者中文文件
        ZipFile zip = new ZipFile(zipFile, StandardCharsets.UTF_8);
        for (Enumeration entries = zip.entries(); entries.hasMoreElements(); ) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            InputStream in = zip.getInputStream(entry);
            String curEntryName = entry.getName();
            // 判断文件名路径是否存在文件夹
            int endIndex = curEntryName.lastIndexOf('/');
            // 替换
            String outPath = (descDir + curEntryName).replaceAll("\\*", "/");
            if (endIndex != -1) {
                File file = new File(outPath.substring(0, outPath.lastIndexOf("/")));
                if (!file.exists()) {
                    file.mkdirs();
                }
            }

            // 判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
            File outFile = new File(outPath);
            if (outFile.isDirectory()) {
                continue;
            }
            OutputStream out = new FileOutputStream(outPath);
            byte[] buf1 = new byte[1024];
            int len;
            while ((len = in.read(buf1)) > 0) {
                out.write(buf1, 0, len);
            }
            in.close();
            out.close();
        }
    }

    /**
     * 解压文件
     *
     * @param inputStream：需要解压缩的文件
     * @param descDir：解压后的目标目录
     */
    public static void unZipFiles(InputStream inputStream, String descDir) throws IOException {
        try (
                //指定需要解压缩的zip文件
                ZipInputStream zipInputStream = new ZipInputStream(inputStream)
        ) {
            ZipEntry zipEntry;
            byte[] byteArray;
            int len;
            //遍历zip文件中的所有项，并逐个解压到指定的目录中
            while ((zipEntry = zipInputStream.getNextEntry()) != null) {
                try (FileOutputStream fileOutputStream = new FileOutputStream(descDir)) {
                    byteArray = new byte[1024];
                    while ((len = zipInputStream.read(byteArray)) != -1) {
                        fileOutputStream.write(byteArray, 0, len);
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}